package com.pashanhoo.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author 胡庆安
 * @version V1.0
 * @Package com.pashanhoo.netty.http
 * @date 2020/11/6 14:04
 * @Copyright © 2010-2020 爬山虎科技（扬州）股份有限公司
 */
//1.SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
//2.HttpObject 客户端和服务器端互相通讯的数据被封装成 HttpObject
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断msg是否是httpRequest请求
        if (msg instanceof HttpRequest){

            System.out.println("msg类型="+msg.getClass());
            System.out.println("客户端地址="+ctx.channel().remoteAddress());

            //回复信息给浏览器【http协议】

            ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);

            //构造一个http的响应，即httpresponse

            FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
        }
    }
}
